/**
 * 所属节点：盘点单创建
 * 创建人：zm
 * 创建时间：2024年8月27日++++++++++++++++++++++++++++
 * 最后修改人：zm
 */
cb.define(process.env.__DOMAINKEY__, function () {
  let GDGY01_dxq_checkstock_create_VM_Extend = {
    doAction: function (name, viewModel) {
      if (this[name]) this[name](viewModel);
    },
    init: function (viewModel) {
      const qianzhui = "/gdgy/pc/isv2";
      let userInfo = viewModel.getAppContext().user;
      let tenantID = viewModel.getAppContext().tenant.tenantId;
      var alternativeTable = [];
      viewModel.on("customInit", function (data) {
        // 盘点单创建详情--页面初始化
        // console.log(viewModel.getParams());
        let tenantID = viewModel.getAppContext().tenant.tenantId;
        let userInfo = viewModel.getAppContext().user;
        viewModel.getParams().autoLoad = false;
        viewModel.getParams().autoAddRow = false;
        var GridModel1 = viewModel.get("dxq_checkstockSonList");
        var GridModel2 = viewModel.get("dxq_checkstockAreaList");
        var checkTypeModel = viewModel.get("checkType"); //盘点类型
        var sourceTypeModel = viewModel.get("sourceType"); //单据源类型
        var remarkModel = viewModel.get("cRemark"); //备注

        var warehouse = viewModel.get("warehouseId_name");
        warehouse.on("afterValueChange", function (data) {
          alternativeTable = [];
        });

        var sourceType = viewModel.get("sourceType");
        sourceType.on("afterValueChange", function (data) {
          alternativeTable = [];
        });

        GridModel1.setState("dataSourceMode", "local");
        GridModel2.setState("dataSourceMode", "local");
        GridModel1.setDataSource(alternativeTable);
        GridModel2.setDataSource(alternativeTable);

        viewModel.on("afterMount", function () {
          checkTypeModel.setState("dataSourceMode", "local");
          checkTypeModel.setDataSource([{ value: "1", text: "任务盘点", nameType: "string" }]);
          sourceTypeModel.setState("dataSourceMode", "local");
          sourceTypeModel.setDataSource([
            { value: "1", text: "按照区域盘点", nameType: "string" },
            { value: "2", text: "按照货架盘点", nameType: "string" },
          ]);
        });

        // A function about getting array index.
        function getIndexOf(arrayTable, val, warehouseCode) {
          for (var i = 0; i < arrayTable.length; i++) {
            // console.log("++++++++++++++++++++++++++++++++++++++++++++");
            // console.log(arrayTable[i].locationCode);
            if (arrayTable[i].locationCode == val && arrayTable[i].warehouseCode == warehouseCode) {
              // console.log(arrayTable[i].locationCode, val);
              return i;
            }
          }
          return -1;
        }

        //单个盘点范围选中，添加到盘点单子表中
        GridModel1.on("afterSelect", function (rowIndexs) {
          var index = GridModel1.getFocusedRowIndex();
          var currentRow = GridModel1.getRow(index);
          //var currentRow = GridModel1.getRow(rowIndexs);

          var obj = {};
          obj.locationName = currentRow.locationName;
          obj.locationCode = currentRow.locationCode;
          obj.warehouseCode = currentRow.warehouseCode;
          obj.warehouseName = currentRow.warehouseName;
          obj.locationID = currentRow.locationID;
          obj.RFIDCode = currentRow.RFIDCode;
          //console.log(obj);
          if (currentRow.locationID !== undefined) {
            //console.log(currentRow);
            alternativeTable.push(obj);
          }

          GridModel2.setReadOnly(true);
          GridModel2.clear();
          GridModel2.setDataSource(alternativeTable);
        });

        //单个盘点范围取消选中，删除盘点单子表中的盘点范围
        GridModel1.on("afterUnselect", function (rowIndexs) {
          var currentRow = GridModel1.getRow(rowIndexs);
          //console.log(currentRow.locationCode);
          var indexof = getIndexOf(alternativeTable, currentRow.locationCode, currentRow.warehouse_code);
          //console.log("---------------------------------");
          // console.log(indexof);
          alternativeTable.splice(indexof, 1); //删除取消选中的数据

          GridModel2.setDataSource(alternativeTable);
          GridModel2.setReadOnly(true);
        });
      });

      viewModel.get("warehouseId_name") &&
        viewModel.get("warehouseId_name").on("afterValueChange", function (data) {
          // 仓库--值改变后
          viewModel.getParams().autoLoad = false;
          const GridModel1 = viewModel.get("dxq_checkstockSonList");
          const GridModel2 = viewModel.get("dxq_checkstockAreaList");
          var warehouse = viewModel.get("warehouseId").getValue();
          var sourceType = viewModel.get("sourceType").getValue();
          var domainKey = viewModel.getDomainKey();
          // console.log(domainKey);
          // console.log(sourceType);
          if (sourceType != null && sourceType != undefined) {
            // cb.rest.invokeFunction(
            //   "GDGY01.Location.getlocationData",
            //   { warehouseID: warehouse, sourceType: sourceType },
            //   function (err, res) {
            //     GridModel2.clear();
            //     GridModel1.setState("dataSourceMode", "local");
            //     console.log(res);
            //     GridModel1.setDataSource(res.rst);
            //     GridModel2.setState("dataSourceMode", "local");
            //     GridModel1.setReadOnly(true);
            //     GridModel2.setReadOnly(true);
            //   }
            // );
            /**
             * 张明迁移
             */
            const url_getdata =
              qianzhui +
              "/location/getlocationList?tenant_id=" +
              tenantID +
              "&warehouseId=" +
              warehouse +
              "&level=" +
              sourceType;
            const proxy_getdata = viewModel.setProxy({
              getdata: {
                url: url_getdata,
                method: "GET",
              },
            });
            proxy_getdata.getdata({}, function (err, res) {
              GridModel2.clear();
              GridModel1.setState("dataSourceMode", "local");
              GridModel1.setDataSource(res.dataList);
              GridModel2.setState("dataSourceMode", "local");
              GridModel1.setReadOnly(true);
              GridModel2.setReadOnly(true);
            });
          }
        });

      viewModel.get("sourceType") &&
        viewModel.get("sourceType").on("afterValueChange", function (data) {
          // 单据源类型--值改变后
          viewModel.getParams().autoLoad = false;
          const GridModel1 = viewModel.get("dxq_checkstockSonList");
          const GridModel2 = viewModel.get("dxq_checkstockAreaList");
          var warehouse = viewModel.get("warehouseId").getValue();
          if (warehouse != null) {
            var sourceType = viewModel.get("sourceType").getValue();
            // console.log(sourceType);
            if (sourceType === null || sourceType === "" || sourceType === undefined) {
              GridModel2.clear();
              GridModel1.setState("dataSourceMode", "local");
              GridModel1.setDataSource([]);
              GridModel2.setState("dataSourceMode", "local");
              GridModel2.setDataSource([]);
              GridModel1.setReadOnly(true);
              GridModel2.setReadOnly(true);
            } else {
              var domainKey = viewModel.getDomainKey();
              // console.log(domainKey);
              // console.log(sourceType);
              // cb.rest.invokeFunction(
              //   "GDGY01.Location.getlocationData",
              //   { warehouseID: warehouse, sourceType: sourceType },
              //   function (err, res) {
              //     GridModel2.clear();
              //     GridModel1.setState("dataSourceMode", "local");
              //     // console.log(err);
              //     // console.log(res);
              //     GridModel1.setDataSource(res.rst);
              //     GridModel2.setState("dataSourceMode", "local");
              //     GridModel1.setReadOnly(true);
              //     GridModel2.setReadOnly(true);
              //   }
              // );
              /**
               * 张明迁移
               */
              const url_getdata =
                qianzhui +
                "/location/getlocationList?tenant_id=" +
                tenantID +
                "&warehouseId=" +
                warehouse +
                "&level=" +
                sourceType;
              const proxy_getdata = viewModel.setProxy({
                getdata: {
                  url: url_getdata,
                  method: "GET",
                },
              });
              proxy_getdata.getdata({}, function (err, res) {
                GridModel2.clear();
                GridModel1.setState("dataSourceMode", "local");
                GridModel1.setDataSource(res.dataList);
                GridModel2.setState("dataSourceMode", "local");
                GridModel1.setReadOnly(true);
                GridModel2.setReadOnly(true);
              });
            }
          }
        });

      viewModel.get("btnSaveAndAdd") &&
        viewModel.get("btnSaveAndAdd").on("click", function (data) {
          // 保存并新增--单击
          var userID = viewModel.getAppContext().user.userId;
          const GridModel2 = viewModel.get("dxq_checkstockAreaList");
          var locationarr = [];
          var sonOrder = {};
          let yearStr = new Date().getFullYear();
          let monthStr = new Date().getMonth() + 1;
          let dateStr = new Date().getDate();
          let hourStr = new Date().getHours();
          let minuteStr = new Date().getMinutes();
          let secondStr = new Date().getSeconds();

          if (monthStr < 10) {
            monthStr = "0" + String(monthStr);
          } else {
            monthStr = String(monthStr);
          }

          if (dateStr < 10) {
            dateStr = "0" + String(dateStr);
          } else {
            dateStr = String(dateStr);
          }

          if (hourStr < 10) {
            hourStr = "0" + String(hourStr);
          } else {
            hourStr = String(hourStr);
          }

          if (minuteStr < 10) {
            minuteStr = "0" + String(minuteStr);
          } else {
            minuteStr = String(minuteStr);
          }

          if (secondStr < 10) {
            secondStr = "0" + String(secondStr);
          } else {
            secondStr = String(secondStr);
          }

          let suijiCode =
            String(yearStr) + monthStr + String(dateStr) + String(hourStr) + String(minuteStr) + String(secondStr);
          // console.log(suijiCode);
          var warehouseId = viewModel.get("warehouseId").getValue();
          var warehousename = viewModel.get("warehouseId_name").getValue();
          var checkType =
            viewModel.get("checkType").getValue() === undefined || viewModel.get("checkType").getValue() === null
              ? 1
              : viewModel.get("checkType").getValue();
          var sourceType = viewModel.get("sourceType").getValue();
          var remark = viewModel.get("cRemark").getValue() === undefined ? "" : viewModel.get("cRemark").getValue();

          var tableDatas = GridModel2.getRows();
          // console.log(tableDatas.length);
          if (tableDatas.length === 0) {
            cb.utils.alert("请先选中要生成盘点单的数据!");
          } else {
            var timestr = new Date().format("yyyy-MM-dd hh:mm:ss");
            tableDatas.forEach(function (element) {
              var sonData = {};
              // console.log(element);
              if (element.RFIDCode == undefined) {
                sonData.RFIDCode = "";
              } else {
                sonData.RFIDCode = element.RFIDCode;
              }
              sonData.iStatus = 0;
              sonData.locationCode = element.locationCode;
              sonData.locationID = element.locationID;
              sonData.locationName = element.locationName;
              sonData.warehouseName = element.warehouseName;
              sonData.warehouseCode = element.warehouseCode;
              sonData.creator = userID;
              sonData.createTime = timestr;
              locationarr.push(sonData);
            });
            // console.log(locationarr);

            // cb.rest.invokeFunction(
            //   "GDGY01.pandian.Creattakestock",
            //   {
            //     billNum: "dxq_checkstockList",
            //     warehouseId: warehouseId,
            //     sourceType: sourceType,
            //     checkType: checkType,
            //     warehouseName: warehousename,
            //     Codesuiji: suijiCode,
            //     locationarr: locationarr,
            //     cRemark: remark,
            //   },
            //   function (err, res) {
            //     // console.log(res);
            //     // console.log(err);
            //     if (res !== null && res !== undefined && err === null) {
            //       // console.log(err);
            //       // console.log(res);
            //       cb.utils.alert("成功生成盘点单！");
            //       viewModel.clear();
            //     }
            //   }
            // );
            /**
             * 张明迁移
             */
            const url_Creattakestock =
              qianzhui + "/checkstock/CreatCheckStock?tenant_id=" + tenantID + "&userId=" + userInfo.userId;
            const proxy_Creattakestock = viewModel.setProxy({
              Creattakestock: {
                url: url_Creattakestock,
                method: "POST",
              },
            });
            proxy_Creattakestock.Creattakestock(
              {
                warehouseId: warehouseId,
                sourceType: sourceType,
                checkType: checkType,
                warehouseName: warehousename,
                Codesuiji: suijiCode,
                locationarr: locationarr,
                cRemark: remark,
              },
              function (err, res) {
                if (res !== null && res !== undefined && err === null) {
                  // console.log(err);
                  // console.log(res);
                  cb.utils.alert("成功生成盘点单！");
                  viewModel.clear();
                }
              }
            );
          }
        });

      viewModel.get("btnSave") &&
        viewModel.get("btnSave").on("click", function (data) {
          // 保存--单击
          var userID = viewModel.getAppContext().user.userId;
          const GridModel2 = viewModel.get("dxq_checkstockAreaList");
          var locationarr = [];
          var sonOrder = {};
          let yearStr = new Date().getFullYear();
          let monthStr = new Date().getMonth() + 1;
          let dateStr = new Date().getDate();
          let hourStr = new Date().getHours();
          let minuteStr = new Date().getMinutes();
          let secondStr = new Date().getSeconds();

          if (monthStr < 10) {
            monthStr = "0" + String(monthStr);
          } else {
            monthStr = String(monthStr);
          }

          if (dateStr < 10) {
            dateStr = "0" + String(dateStr);
          } else {
            dateStr = String(dateStr);
          }

          if (hourStr < 10) {
            hourStr = "0" + String(hourStr);
          } else {
            hourStr = String(hourStr);
          }

          if (minuteStr < 10) {
            minuteStr = "0" + String(minuteStr);
          } else {
            minuteStr = String(minuteStr);
          }

          if (secondStr < 10) {
            secondStr = "0" + String(secondStr);
          } else {
            secondStr = String(secondStr);
          }

          let suijiCode =
            String(yearStr) + monthStr + String(dateStr) + String(hourStr) + String(minuteStr) + String(secondStr);
          // console.log(suijiCode);
          var warehouseId = viewModel.get("warehouseId").getValue();
          var warehousename = viewModel.get("warehouseId_name").getValue();
          var checkType =
            viewModel.get("checkType").getValue() === undefined || viewModel.get("checkType").getValue() === null
              ? 1
              : viewModel.get("checkType").getValue();
          var sourceType = viewModel.get("sourceType").getValue();
          var remark = viewModel.get("cRemark").getValue() === undefined ? "" : viewModel.get("cRemark").getValue();
          var tableDatas = GridModel2.getRows();
          // console.log(tableDatas.length);
          if (tableDatas.length === 0) {
            cb.utils.alert("请先选中要生成盘点单的数据!");
          } else {
            var timestr = new Date().format("yyyy-MM-dd hh:mm:ss");
            tableDatas.forEach(function (element) {
              var sonData = {};
              // console.log(element);
              if (element.RFIDCode == undefined) {
                sonData.RFIDCode = "";
              } else {
                sonData.RFIDCode = element.RFIDCode;
              }
              sonData.iStatus = 0;
              sonData.locationCode = element.locationCode;
              sonData.locationID = element.locationID;
              sonData.locationName = element.locationName;
              sonData.warehouseName = element.warehouseName;
              sonData.warehouseCode = element.warehouseCode;
              sonData.creator = userID;
              sonData.createTime = timestr;
              locationarr.push(sonData);
            });
            // console.log(locationarr);

            // cb.rest.invokeFunction(
            //   "GDGY01.pandian.Creattakestock",
            //   {
            //     billNum: "dxq_checkstockList",
            //     warehouseId: warehouseId,
            //     sourceType: sourceType,
            //     checkType: checkType,
            //     warehouseName: warehousename,
            //     Codesuiji: suijiCode,
            //     locationarr: locationarr,
            //     cRemark: remark,
            //   },
            //   function (err, res) {
            //     // console.log(res);
            //     // console.log(err);
            //     if (res !== null && res !== undefined && err === null) {
            //       // console.log(err);
            //       // console.log(res);
            //       cb.utils.alert("成功生成盘点单！");

            //       let data1 = {
            //         billtype: "Voucher", // 单据类型
            //         billno: "dxq_checkstockList", // 单据号
            //         params: {
            //           mode: "browse", // (编辑态edit、新增态add、浏览态browse)
            //         },
            //       };
            //       //打开一个单据，并在当前页面显示
            //       cb.loader.runCommandLine("bill", data1, viewModel);
            //     }
            //   }
            // );
            /**
             * 张明迁移
             */
            const url_Creattakestockand =
              qianzhui + "/checkstock/CreatCheckStock?tenant_id=" + tenantID + "&userId=" + userInfo.userId;
            const proxy_Creattakestockand = viewModel.setProxy({
              Creattakestockand: {
                url: url_Creattakestockand,
                method: "POST",
              },
            });
            proxy_Creattakestockand.Creattakestockand(
              {
                billNum: "dxq_checkstockList",
                warehouseId: warehouseId,
                sourceType: sourceType,
                checkType: checkType,
                warehouseName: warehousename,
                Codesuiji: suijiCode,
                locationarr: locationarr,
                cRemark: remark,
              },
              function (err, res) {
                // console.log(res);
                // console.log(err);
                if (res !== null && res !== undefined && err === null) {
                  // console.log(err);
                  // console.log(res);
                  cb.utils.alert("成功生成盘点单！");

                  let data1 = {
                    billtype: "Voucher", // 单据类型
                    billno: "dxq_checkstockList", // 单据号
                    params: {
                      mode: "browse", // (编辑态edit、新增态add、浏览态browse)
                    },
                  };
                  //打开一个单据，并在当前页面显示
                  cb.loader.runCommandLine("bill", data1, viewModel);
                }
              }
            );
          }
        });

      //盘点范围全选，将所有信息添加到盘点单子表
      viewModel.getGridModel("dxq_checkstockSonList") &&
        viewModel.getGridModel("dxq_checkstockSonList").on("afterSelectAll", function (data) {
          //表格-盘点单子单备选表--全选后
          alternativeTable = []; //清空数据
          //console.log("======"+data);
          for (var i = 0; i < data.length; i++) {
            var currentRow = data[i];
            var obj = {};
            obj.locationName = currentRow.locationName;
            obj.locationCode = currentRow.locationCode;
            obj.warehouseCode = currentRow.warehouseCode;
            obj.warehouseName = currentRow.warehouseName;
            obj.locationID = currentRow.locationID;
            obj.RFIDCode = currentRow.RFIDCode;
            if (currentRow.locationID !== undefined) {
              alternativeTable.push(obj);
            }
          }

          var GridModel2 = viewModel.get("dxq_checkstockAreaList");
          GridModel2.setReadOnly(true);
          GridModel2.clear();
          GridModel2.setDataSource(alternativeTable);
        });

      //盘点范围全不选，将盘点单子表中数据全部删除
      viewModel.getGridModel("dxq_checkstockSonList") &&
        viewModel.getGridModel("dxq_checkstockSonList").on("afterUnselectAll", function (data) {
          //表格-盘点单子单表--取消全选后
          alternativeTable = []; //清空数据

          var GridModel2 = viewModel.get("dxq_checkstockAreaList");
          GridModel2.setReadOnly(true);
          GridModel2.clear();
          GridModel2.setDataSource(alternativeTable);
        });
    },
  };
  try {
    module.exports = GDGY01_dxq_checkstock_create_VM_Extend;
  } catch (error) {}
  return GDGY01_dxq_checkstock_create_VM_Extend;
});
